package org.yangspring.samples.mvc.daoOracle;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.yangspring.samples.mvc.domainOracle.DBATables;
import org.yangspring.samples.mvc.listeners.ContentEvent;

import java.util.List;

import static java.lang.System.out;

/**
 * Created by franklin on 6/24/2017.
 */

@Repository
public class DBATablesDAOImpl implements DBATablesDAO, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(DBATablesDAOImpl.class);

    @Autowired
    @Qualifier("hibernate5AnnotatedSessionFactoryOracle")
    private SessionFactory sessionFactory;

    private ApplicationContext appCntx;

    public void setApplicationContext(ApplicationContext appCntx){
        this.appCntx = appCntx;
    }

    /*public void setSessionFactory(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }*/

    public List<DBATables> listDbaTables(){
//        Session session = this.sessionFactory.getCurrentSession();
//        List<DBATables> dbaTablesList = session.createQuery("from Customers").list();
        Session session = this.sessionFactory.openSession();
        TransactionSynchronizationManager.bindResource(this.sessionFactory, session);

        logger.warn("\nDBATablesDAOImpl\n");

        List<DBATables> dbaTablesList = session.createSQLQuery("select TABLE_NAME, OWNER, TABLESPACE_NAME, STATUS, DEGREE," +
                "INSTANCES, CACHE, TABLE_LOCK, GLOBAL_STATS, USER_STATS " +
                "from DBA_TABLES" ).addEntity(DBATables.class).list();
//        List<DBATables> dbaTablesList = session.createSQLQuery("select * from DBA_TABLES" ).addEntity(DBATables.class).list();

        /*****
         * 上面三种方式都OK！
         * 联合查询，也是基本相同！
         * ***/

        if (dbaTablesList.size() < 1){
            logger.warn("\n\ndbaTablesList has nothing !\n");
        }

        for(DBATables t : dbaTablesList){
            logger.info("DBATables List::" + t);
        }
        return dbaTablesList;
    }


    public List<DBATables> listDbaTables4Owner(String owner){
//        Session session = this.sessionFactory.getCurrentSession();
        Session session = this.sessionFactory.openSession();
        TransactionSynchronizationManager.bindResource(this.sessionFactory, session);

        logger.warn("\nDBATablesDAOImpl for Owner\n");

        List<DBATables> dbaTablesList = session.createSQLQuery("select TABLE_NAME, OWNER, TABLESPACE_NAME, STATUS, DEGREE, " +
                "INSTANCES, CACHE, TABLE_LOCK, GLOBAL_STATS, USER_STATS " +
                "from DBA_TABLES " +
                "where owner = '" + owner.toUpperCase() + "'").addEntity(DBATables.class).list();
//        List<DBATables> dbaTablesList = session.createSQLQuery("select * from DBA_TABLES" ).addEntity(DBATables.class).list();

        return dbaTablesList;
    }

    public List<DBATables> listDbaTables4Name4Name(String name){
        Session session = null;
//        Session session = this.sessionFactory.getCurrentSession();

        session = this.sessionFactory.openSession();
//        if(TransactionSynchronizationManager.getResource(this.sessionFactory) == null){
//            TransactionSynchronizationManager.bindResource(this.sessionFactory, session);
//        }
        TransactionSynchronizationManager.bindResource(this.sessionFactory, session);
//        if(!TransactionSynchronizationManager.isActualTransactionActive()){
//        }

        logger.warn("\nDBATablesDAOImpl for Owner\n");
        /*TEXT, */
        List<DBATables> dbaTablesList = session.createSQLQuery("select TABLE_NAME, OWNER, TABLESPACE_NAME, STATUS, DEGREE, " +
                "INSTANCES, CACHE, TABLE_LOCK, GLOBAL_STATS, USER_STATS " +
                "from DBA_TABLES " +
                "where table_name like '%" + name.toUpperCase() + "%'").addEntity(DBATables.class).list();

        return dbaTablesList;
    }

    public List<DBATables> listDbaTables4NameOwner(String name, String owner){

        Session session = null;
//        Session session = this.sessionFactory.getCurrentSession();

        session = this.sessionFactory.openSession();
        if (session.getSessionFactory() == null){
            TransactionSynchronizationManager.bindResource(this.sessionFactory, session);
        }

        logger.warn("\nDBAViewsDAOImpl for Name and Owner\n");
        this.appCntx.publishEvent(new ContentEvent("Now FrankieYang 's Blog Updating from DBATablesDAOImpl\n"));
        this.appCntx.publishEvent(new ApplicationEvent("Now WHYANG 's Blog Updating from DBATablesDAOImpl\n") {
            @Override
            public Object getSource() {
                return super.getSource();
            }
        });

        /*TEXT, */
        List<DBATables> dbaTablesList = session.createSQLQuery("select TABLE_NAME, OWNER, TABLESPACE_NAME, STATUS, DEGREE, " +
                "INSTANCES, CACHE, TABLE_LOCK, GLOBAL_STATS, USER_STATS " +
                "from DBA_TABLES " +
                "where " + ((name == "") ? "" : ("table_name like '%" + name.toUpperCase() + "%' and")) + " owner = '" + owner.toUpperCase() + "'").addEntity(DBATables.class).list();

        return dbaTablesList;
    }

}
